package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.*;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders, HttpSession session) {
        log.info("用户下单参数:{}", orders.toString());
        Orders orders1 = orderService.submit(orders);
        session.setAttribute("orders",orders1);

        return R.success("订单提交成功!");
    }

    /**
     * 订单条件分页查询
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number,
                        @DateTimeFormat String beginTime,
                        @DateTimeFormat String endTime) {
        //System.out.println(beginTime.toString());
        log.info(endTime);
        //System.out.println(beginTime.getClass());
        //1.构建分页查询器;
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //2.构建条件查询器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(number != null, Orders::getNumber, number);
        queryWrapper.between(beginTime != null && endTime != null, Orders::getCheckoutTime, beginTime, endTime);
        queryWrapper.orderByDesc(Orders::getOrderTime);//根据下单时间降序展示
        //3.进行查询
        Page<Orders> ordersPage = orderService.page(pageInfo, queryWrapper);

        return R.success(ordersPage);
    }

    /**
     * 更新订单配送状态
     *
     * @param order
     * @return
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders order) {
        //1.通过id查询需要修改的订单信息
        orderService.updateById(order);
        return R.success("订单状态更新成功!");
    }

    /**
     * 前端展示订单信息
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> pageDto = new Page<>();

        orderService.page(pageInfo);
        // 将其除了records中的内存复制到pageDto中
        BeanUtils.copyProperties(pageInfo, pageDto, "records");

        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> collect = records.stream().map((order) -> {
            OrdersDto ordersDto = new OrdersDto();

            BeanUtils.copyProperties(order, ordersDto);
            // 根据订单id查询订单详细信息

            QueryWrapper<OrderDetail> wrapperDetail = new QueryWrapper<>();
            wrapperDetail.eq("order_id", order.getId());

            List<OrderDetail> orderDetails = orderDetailService.list(wrapperDetail);
            ordersDto.setOrderDetails(orderDetails);

            // 根据userId 查询用户姓名
            Long userId = order.getUserId();
            User user = userService.getById(userId);
            ordersDto.setUserName(user.getName());
            ordersDto.setPhone(user.getPhone());

            // 获取地址信息
            Long addressBookId = order.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);
            ordersDto.setAddress(addressBook.getDetail());
            ordersDto.setConsignee(addressBook.getConsignee());

            return ordersDto;
        }).collect(Collectors.toList());

        pageDto.setRecords(collect);
        return R.success(pageDto);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        //1.通过id查询订单
        Long id = orders.getId();//获取原套餐的id
        orders = orderService.getById(id);//通过id查询订单信息
        orders.setId(null);//将id置为null;

        //2.在明细表里查询订单明细信息
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, id);
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        //3.将明细表中的id置为null
        List<OrderDetail> newList = new ArrayList<>();
        for (OrderDetail orderDetail : list) {
            ShoppingCart shoppingCart = new ShoppingCart();
            orderDetail.setId(null);
            orderDetail.setOrderId(null);
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            Long currentId = BaseContext.getCurrentId();
            shoppingCart.setUserId(currentId);
            shoppingCartService.save(shoppingCart);
        }

        return R.success("success");
    }
}
